﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LanguageFeatures.Models
{
    public static class ShoppingCartExtension
    {
        public static decimal TotalAmount(this IEnumerable<Product> products)
        {
            decimal total = 0;
            foreach(Product p in products) {
                total += p?.Price ?? 0;
            }

            return total;
        }

        /// <summary>
        /// 筛选出最小价格以上的所有产品
        /// </summary>
        /// <param name="products"></param>
        /// <param name="minimumPrice"></param>
        /// <returns></returns>
        public static IEnumerable<Product> FilterByPrice(this IEnumerable<Product> products, 
            decimal minimumPrice)
        {
            foreach(Product prod in products) {
                if ((prod?.Price ?? 0) >= minimumPrice) {
                    yield return prod;
                }
            }
        }

        /// <summary>
        /// 实现一个通用的Filter程序
        /// </summary>
        /// <param name="productEnum"></param>
        /// <param name="selector"></param>
        /// <returns></returns>
        public static IEnumerable<Product> Filter(this IEnumerable<Product> productEnum, Func<Product, bool> selector)
        {
            foreach(Product prod in productEnum) {
                if (selector(prod)) {
                    yield return prod;
                }
            }
        }
    }
}
